package com._58city.spark.app.redis;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.SafeEncoder;

import com._58city.spark.app.ext.JsonUtil;
import com.bj58.ecdata.redis.JedisBean;
import com.bj58.ecdata.redis.JedisX;

/**
 * @author lihao
 * Redis的工具类
 */
public class RedisUtil {
	
	private static Logger log = LoggerFactory.getLogger(RedisUtil.class);

	static{
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxActive(500); //如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
		config.setMaxIdle(100);  //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
		
		config.setMaxWait(2000); //表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException
		config.setTestOnBorrow(false); // //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
		
		JedisBean bean = new JedisBean();
		
//		bean.setMasterAddress("10.126.86.167:6379");//新机房线上正式环境
		bean.setMasterAddress("10.9.19.123:6379");//新机房线上正式环境
		
	    cache = new JedisX(bean, config, 7000);
	}
	
	public static JedisX cache;
	
	
    public static <T> void send(String key,List<T> list){
		ShardedJedisPool pool = cache.getShardedJedisPool();
		ShardedJedis shardJedis = null;	
		Jedis jedis = null;	 
		try {
			shardJedis = pool.getResource();
			jedis = shardJedis.getShard(key);
			if (jedis != null) {
				byte[] bytekey = SafeEncoder.encode(key);
				for(T t : list){
					byte[] bytevalue = SafeEncoder.encode(JsonUtil.toJson(t));
					jedis.lpush(bytekey, bytevalue);
				}
			}
		} catch (Exception e) {
			if (shardJedis != null) pool.returnBrokenResource(shardJedis);
			log.error(e.getMessage(), e);
		}finally{
			if (shardJedis != null) pool.returnResource(shardJedis);
		}
	}
    
	
	
}
